import React, { useEffect, useState, useCallback, useRef } from 'react';
import { Card, List, Button, message, Empty, Tag, Modal, Spin, Result, Typography, Progress, Alert } from 'antd';
import { CheckCircleOutlined, ClockCircleOutlined, ReloadOutlined, BookOutlined, EnvironmentOutlined, CameraOutlined, UserAddOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { fetchPendingTasks, performSignIn, clearError } from '../../store/slices/signInSlice';
import FaceCapture from '../../components/FaceCapture';
import './index.scss';
import { signInAPI, teacherAPI, studentCourseAPI } from '../../services/api';
import axios from 'axios';

const { Title, Text, Paragraph } = Typography;

const SignIn = () => {
  const dispatch = useDispatch();
  const { pendingTasks, loading, error } = useSelector((state) => state.signIn);
  const [refreshing, setRefreshing] = useState(false);
  const [loadingTaskId, setLoadingTaskId] = useState(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentTask, setCurrentTask] = useState(null);
  const [faceImage, setFaceImage] = useState(null);
  const [location, setLocation] = useState(null);
  const locationInitialized = useRef(false);
  const [debugInfo, setDebugInfo] = useState(null);

  // 获取待签到任务 
  const fetchTasks = useCallback(async () => {
    setRefreshing(true);
    try {
      // 先清除之前的错误
      dispatch(clearError());
      console.log('开始获取待签到任务...');
      
      // 使用Redux action获取签到任务
      const response = await dispatch(fetchPendingTasks()).unwrap();
      console.log('获取待签到任务响应:', response);
      
      // 检查结果是否为空数组
      if (Array.isArray(response) && response.length === 0) {
        console.log('获取到空签到任务列表');
      }
      
      // 显示调试信息
      setDebugInfo({
        requestUrl: '/student/sign_in/tasks',
        responseStatus: 200,
        responseData: JSON.stringify(response || [], null, 2)
      });
    } catch (error) {
      console.error('获取任务异常:', error);
      
      // 显示错误调试信息
      setDebugInfo({
        requestUrl: '/student/sign_in/tasks',
        error: error.message,
        errorDetails: error.response ? JSON.stringify(error.response.data, null, 2) : '无响应数据'
      });
      
      message.error('获取签到任务失败: ' + (error.message || '未知错误'));
    } finally {
      setRefreshing(false);
    }
  }, [dispatch]);

  useEffect(() => {
    fetchTasks();
    
    // 设置自动刷新定时器，每30秒自动刷新一次
    const refreshInterval = setInterval(() => {
      fetchTasks();
    }, 30000);

    return () => clearInterval(refreshInterval);
  }, [fetchTasks]);

  // 获取地理位置信息的函数，但只在用户交互时调用
  const getLocation = useCallback(() => {
    if (navigator.geolocation && !location && !locationInitialized.current) {
      locationInitialized.current = true;
      navigator.geolocation.getCurrentPosition(
        position => {
          setLocation({
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            accuracy: position.coords.accuracy
          });
          console.log("位置信息获取成功:", {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            accuracy: position.coords.accuracy
          });
        },
        error => {
          console.error('获取位置失败:', error);
          message.warning('无法获取位置信息，签到将不包含位置数据');
          locationInitialized.current = false;
        },
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 }
      );
    }
  }, [location]);

  const formatTime = (timestamp) => {
    return new Date(timestamp * 1000).toLocaleString();
  };

  const openSignInModal = (task) => {
    setCurrentTask(task);
    setModalVisible(true);
    setFaceImage(null);
    
    // 在用户交互时获取位置
    getLocation();
  };

  const handleCapture = (imgSrc) => {
    setFaceImage(imgSrc);
  };

  const handleSubmitSignIn = async () => {
    if (!faceImage) {
      message.warning('请先拍照');
      return;
    }

    if (!currentTask) {
      message.error('无效的签到任务');
      return;
    }

    setLoadingTaskId(currentTask.id);
    try {
      const signInData = {
        sign_in_task_id: currentTask.id,
        face_image: faceImage
      };
      
      // 如果有位置信息，添加到请求数据中
      if (location) {
        signInData.latitude = location.latitude;
        signInData.longitude = location.longitude;
        signInData.accuracy = location.accuracy;
        signInData.location = `纬度: ${location.latitude}, 经度: ${location.longitude}`;
      }
      
      // 使用Redux action执行签到
      const response = await dispatch(performSignIn(signInData)).unwrap();
      
      message.success('签到成功！');
      // 关闭弹窗
      setModalVisible(false);
      // 刷新待签到任务列表
      setTimeout(() => {
        fetchTasks();
      }, 1000);
    } catch (error) {
      message.error('签到失败: ' + (error || '未知错误'));
      console.error(error);
    } finally {
      setLoadingTaskId(null);
    }
  };

  const getTaskStatus = (task) => {
    const now = Date.now() / 1000;
    if (now < task.start_time) {
      return { status: 'waiting', text: '未开始', color: 'default' };
    } else if (now > task.end_time) {
      return { status: 'expired', text: '已过期', color: 'error' };
    } else {
      return { status: 'active', text: '进行中', color: 'success' };
    }
  };

  const getTimeRemaining = (endTime) => {
    const now = Date.now() / 1000;
    const remaining = endTime - now;
    
    if (remaining <= 0) return '已截止';
    
    const hours = Math.floor(remaining / 3600);
    const minutes = Math.floor((remaining % 3600) / 60);
    
    if (hours > 0) {
      return `${hours}小时${minutes}分钟`;
    } else {
      return `${minutes}分钟${Math.floor(remaining % 60)}秒`;
    }
  };

  const getTimeProgress = (startTime, endTime) => {
    const now = Date.now() / 1000;
    if (now < startTime) return 0;
    if (now > endTime) return 100;
    
    const total = endTime - startTime;
    const elapsed = now - startTime;
    return Math.floor((elapsed / total) * 100);
  };

  return (
    <div className="sign-in-container">
      <Typography>
        <Title level={2}>签到管理</Title>
        <Paragraph>
          这里显示您需要完成的签到任务，请及时签到。
          {pendingTasks.length === 0 && !loading && (
            <span className="no-tasks-tip"> 当前没有需要签到的任务。</span>
          )}
        </Paragraph>
      </Typography>

      {/* 待签到任务列表 */}
      <List
        loading={loading}
        dataSource={pendingTasks}
        renderItem={task => (
          <List.Item className="task-list-item">
            <Card className="task-card" variant="bordered">
              <div className="task-header">
                <div className="task-title">
                  <BookOutlined className="task-icon" />
                  <Title level={5}>{task.description || '课程签到'}</Title>
                  <Tag color={getTaskStatus(task).color}>{getTaskStatus(task).text}</Tag>
                </div>
                <Button
                  type="primary"
                  icon={<CameraOutlined />}
                  onClick={() => openSignInModal(task)}
                  loading={loadingTaskId === task.id}
                  size="middle"
                >
                  签到
                </Button>
              </div>
              
              <div className="task-info">
                <div className="time-info">
                  <div><ClockCircleOutlined /> 开始时间：{formatTime(task.start_time)}</div>
                  <div><ClockCircleOutlined /> 截止时间：{formatTime(task.end_time)}</div>
                </div>
                <div className="course-info">
                  <Text strong>课程ID：{task.course_id}</Text>
                  <Text>课程名称：{task.course_name || '未知课程'}</Text>
                  {getTaskStatus(task).status === 'active' && (
                    <div className="time-remaining">
                      <Text type="warning">剩余时间: {getTimeRemaining(task.end_time)}</Text>
                      <Progress percent={getTimeProgress(task.start_time, task.end_time)} size="small" showInfo={false} 
                        strokeColor={
                          getTimeProgress(task.start_time, task.end_time) > 80 ? '#ff4d4f' : 
                          getTimeProgress(task.start_time, task.end_time) > 50 ? '#faad14' : 
                          '#52c41a'
                        }
                      />
                    </div>
                  )}
                </div>
              </div>
            </Card>
          </List.Item>
        )}
      />

      {/* 摄像头模态框 */}
      <Modal
        title={`${currentTask?.description || '课程签到'}`}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={700}
        destroyOnClose={true}
        maskClosable={false}
        className="signin-modal"
      >
        <div className="camera-modal-content">
          <FaceCapture onCapture={handleCapture} />
          {location && (
            <Text className="location-info">
              <EnvironmentOutlined /> 已获取位置信息
            </Text>
          )}
          <Button
            type="primary"
            disabled={!faceImage}
            loading={loadingTaskId === (currentTask?.id || null)}
            onClick={handleSubmitSignIn}
            style={{ marginTop: 16 }}
          >
            确认签到
          </Button>
        </div>
      </Modal>
    </div>
  );
};

export default SignIn;